/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.jsp;

import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.DynamicAttributes;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.lang.StringUtils;
import org.jbfilter.core.FilterHandler;

public class FilterDelegate<E> implements DynamicAttributes {

	private FilterHandler<E> filterHandler;
	private String varFilteredItems;// mandatory
	private ScopeSupport scopeSupport = new ScopeSupport(JbfilterTag.doFilter);
	private DynamicAttributesSupport dynamicAttributesSupport = new DynamicAttributesSupport();
	
	
	public void filter(JspContext context) throws JspException {
		invokeDynamicAttributes();
		List<E> filteredItems = filterHandler.filter();
		if (filteredItems == null) {
			filteredItems = Collections.emptyList();
		}
		// store the filtered items in the scope
		JbfilterSimpleTagSupport.setAttribute(context, varFilteredItems, filteredItems, scopeSupport.getScope());
	}
	private void invokeDynamicAttributes() throws JspException {
		for (Entry<String, Object> entry : dynamicAttributesSupport.getDynamicAttributes().entrySet()) {
			invokeSetter(entry.getKey(), entry.getValue());
		}
	}
	private void invokeSetter(String tagAttr, Object toSet) throws JspException {
		try {
			MethodUtils.invokeMethod(filterHandler, String.format("set%s", StringUtils.capitalize(tagAttr)), toSet);
		} catch (Exception e) {
			throw new JspException(e);
		}
	}
	public void setFilterHandler(FilterHandler<E> filterHandler) {
		if (filterHandler == null) {
			throw new NullPointerException("FilterHandler is null.");
		}
		this.filterHandler = filterHandler;
	}
	public void setVarFilteredItems(String varFilteredItems) {
		this.varFilteredItems = varFilteredItems;
	}
	public void setScope(String scopeAsString) throws JspException {
		scopeSupport.setScope(scopeAsString);
	}
	@Override
	public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {
		dynamicAttributesSupport.setDynamicAttribute(uri, localName, value);
	}
}
